package top.tagao.yygh.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.URLEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javafx.scene.layout.HBox;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.tagao.yygh.common.helper.JwtHelper;
import top.tagao.yygh.common.result.Result;
import top.tagao.yygh.model.user.UserInfo;
import top.tagao.yygh.user.service.UserInfoService;
import top.tagao.yygh.user.utils.ConstantWxPropertiesUtils;
import top.tagao.yygh.user.utils.HttpClientUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/10 14:31
 */
@Slf4j
@Api(tags = "微信操作的接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private  UserInfoService userInfoService;

    @ApiOperation(value = "通过code 请求得到access_token")
    @GetMapping("callback")
    public String callback(@RequestParam String code,@RequestParam String state) {
        // 1. 获取到临时票据code
        log.info("code : {}", code);
        // 2. 通过 appid secret code 拼接请求 (access_token) 固定路径
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        StringBuilder requestAccessTokenURL = new StringBuilder()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String urlAccessToken = String.format(requestAccessTokenURL.toString(),ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                                            ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                                            code);
        // 3. 通过httpClient 发送请求得到 responseInfo
        try {
            String responseInfo = HttpClientUtils.get(urlAccessToken);
            log.info("responseInfo : {} " ,responseInfo);

            // 通过字符串获取两个值 openid  和  access_token
            JSONObject jsonObject = JSONObject.parseObject(responseInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");


            // 4. 通过openId(唯一标识) 判断数据库是否存在用户 ? {  : 添加用户}
            UserInfo  userInfo =  userInfoService.selectWxInfoOpenId(openid);
            if (userInfo == null) {
                // 5. 通过openid 和 access_token 拼接请求 (userinfo) 固定路径
                //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
                String requestUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=%s" +"&openid=%s";
                String urlUserInfo = String.format(requestUserInfoUrl, access_token, openid);


                // 6. 通过httpClient 发送请求得到 userInfo
                String  responseUserInfo  = HttpClientUtils.get(urlUserInfo);
                log.info("responseUserInfo : {}" ,responseUserInfo);

                // 7. 解析用户信息得到 用户头像 用户图片
                JSONObject resultUserInfoJson = JSONObject.parseObject(responseUserInfo);
                String nickname = resultUserInfoJson.getString("nickname");

                //获取扫描人信息添加数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            // 重定向 参数一: name
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            // 重定向 参数二: token
            String token = JwtHelper.createToken(userInfo.getId(), name);

            // 重定向 参数三: openId
            // 判断userInfo是否有手机号 ? {openid值是空字符串 : 返回openid }
            // 前端 --> 判断openid是为空 ? {不需要绑定手机号  : 绑定手机，}
            if(StringUtils.isEmpty(userInfo.getPhone())) {
               openid =  userInfo.getOpenid();
            } else {
                openid = "";
            }

            return "redirect:" +
                    ConstantWxPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?token="+ token + "&openid="+ openid +"&name="+URLEncoder.encode(name,"utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;


    }



    /**
     * @date  生成二维码
     * @return 返回生成二维码需要的参数
     */
    @ApiOperation(value = "返回生成二维码需要的参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect() {
        try {

            String redirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");

            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("redirect_uri", redirectUrl);
            map.put("scope", "snsapi_login");
            map.put("state", System.currentTimeMillis() + "");
            return  Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }


    }


}
